<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>属性管理</title>
  <link href="../../static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../../static/vendor/bootstrap-icons/bootstrap-icons.min.css" rel="stylesheet">
  <link href="../../static/css/vui365.min.css" rel="stylesheet">
</head>

<body>
  <div id="app">
    <!-- Content Header -->
    <section class="content-header px-4 my-2 border-bottom">
      <h4>属性管理</h4>
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="container-fluid">
        <div class="row">
          <div class="col-12 skeleton">
            <data-table-template>
              <template v-slot:tabsbar>
                <tabsbar></tabsbar>
              </template>
              <template v-slot:searchbar>
                <searchbar @search="onSearch">
                  <select class="border rounded" style="padding:.15rem" v-model="categoryId">
                    <option :value="item.value" v-for="(item,idx) of dataOfCategory" :key="idx">{{item.text}}</option>
                  </select>
                </searchbar>
              </template>
              <template v-slot:toolbar>
                <toolbar @create="onEdit" @edit="onEditMulti" @delete="onDeleteMulti" @toggle-column="onToggleColumn"
                  @refresh="onRefresh"></toolbar>
              </template>
              <template v-slot:paginationbar>
                <paginationbar :page="page" :page-size="pageSize" :total="total" :page-size-list="pageSizeList"
                  :page-list-count="pageListCount" @change-page-size="onChangePageSize" @paging="onPaging">
                </paginationbar>
              </template>
              <template v-slot:table>
                <table class="
                    main-table
                    table
                    table-sm
                    table-bordered
                    table-hover
                    table-striped
                    table-head-fixed
                    m-0
                  ">
                  <thead class="table-light">
                    <tr>
                      <th>
                        <input type="checkbox" title="全选/取消全选" @change="onCheckAll" />
                      </th>
                      <th class="text-nowrap" v-for="(col, idx) of getColumns()" :key="idx">
                        {{ col.text }}
                      </th>
                      <th class="text-nowrap">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(row, idx) of list" :key="idx">
                      <td class="cell-checkbox">
                        <input type="checkbox" :value="row.id" :title="row.id" :checked="row._checked"
                          @change="onCheck($event.target.checked, idx)" />
                      </td>
                      <td v-for="(col, idxCol) of getColumns()" :key="idxCol">
                        <span v-if="col.name=='attr_name'">{{ (row['_prefix']||'')+ row[col.name] }}</span>
                        <span v-else-if="col.name=='icon'"><a :href="row[col.name]" target="_blank"><img class="thumb"
                              :src="row[col.name]" alt="" loading="lazy" /></a></span>
                        <span v-else>{{ row[col.name] }}</span>
                      </td>
                      <td class="text-left text-nowrap">
                        <button class="btn btn-sm btn-secondary" title="编辑" @click="onEdit(row['id'], row, false)">
                          <i class="bi bi-pencil-square"></i>
                        </button>
                        <button class="btn btn-sm btn-secondary" title="规格" @click="onEditSku(row['id'], row)">
                          <i class="bi bi-filter-square"></i>
                        </button>
                        <button class="btn btn-sm btn-secondary" title="删除" @click="onDelete(row['id'])">
                          <i class="bi bi-trash"></i>
                        </button>
                        <button class="btn btn-sm btn-secondary" title="复制" @click="onCopy(row['id'])">
                          <i class="bi bi-files"></i>
                        </button>
                      </td>
                    </tr>
                  </tbody>
                </table>
                <div v-if="total == 0" class="h5dtable-empty-tip text-muted w-100 text-center"
                  style="height: 100px; line-height: 100px">
                  {{isLoading?'正在加载数据...':'抱歉，没有相关数据！'}}
                </div>
              </template>
            </data-table-template>
            <!-- /.card -->
          </div>
          <!-- /.col -->
        </div>
        <!-- /.row -->
      </div>
      <!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>

  <script src="../../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../../static/vendor/vue/vue.global.prod.min.js"></script>
  <script>
    // 全局配置
    this.vui365 = this.parent.vui365;

    // API接口配置
    const UrlCfg = {
      list: '/api/admin/ec-attribute',
      delete: '/api/admin/ec-attribute/{id}',
      copy: '/api/admin/ec-attribute/copy/{id}',
      categoryList: '/api/admin/ec-category?_mode=dict'
    }
    /**
     * 属性组件（）
     * @description 属性组件
     */
    const App = {
      // data 配置
      data() {
        return {
          columns: [],
          list: [],
          total: 0,
          page: 1,
          pageSize: 25,
          pageSizeList: [10, 25, 50, 100, 1000],
          searchText: "",
          categoryId: 0,
          dataOfCategory: [],
          isLoading: true,
        };
      },
      // methods 配置
      methods: {
        // 初始化页面数据
        async initData() {
          await this.onRefresh();
          await this.onLoadCategoryData();
        },
        // 初始化页面视图
        initView() {
          // 移除骨架屏
          document.querySelectorAll('.skeleton').forEach(el => {
            el.classList.remove("skeleton");
          })
        },
        // 加载商品类别数据
        async onLoadCategoryData() {
          vui365.globalApp.showLoading();
          const msgInfo = await vui365.stdAxios(UrlCfg.categoryList, {}, 'GET');
          vui365.globalApp.hideLoading();
          if (msgInfo.status == 0) {
            vui365.BsDialog.alert(msgInfo.message);
            return;
          }
          this.dataOfCategory = msgInfo.data;
        },
        // 处理刷新事件
        async onRefresh() {
          let queryParam = {
            page: this.page,
            page_size: this.pageSize,
            search_text: this.searchText,
            category_id: this.categoryId,
          };
          console.log("[刷新表格数据] queryParam=", queryParam);
          this.isLoading = true;
          vui365.globalApp.showLoading();
          const msgInfo = await vui365.stdAxios(UrlCfg.list, queryParam, 'GET');
          this.isLoading = false;
          vui365.globalApp.hideLoading();
          console.log("[刷新表格数据] msgInfo=", msgInfo);
          if (msgInfo.status == 0) {
            vui365.BsDialog.alert(msgInfo.message);
            return;
          }
          this.list = msgInfo.data.data;
          this.total = msgInfo.data.total;
          console.log("[刷新表格数据] data=", this.total, this.list);
        },
        // 处理编辑事件
        async onEdit(id = 0, row) {
          let title = "添加属性";
          if (id > 0) {
            title = "编辑 " + (row["attr_name"] || "");
          }
          vui365.globalApp.showFormDialog(title, ('ec-attribute/edit.html?id=' + id), window);
        },
        // 处理删除事件
        async onDelete(id) {
          if (Array.isArray(id)) {
            id = id.join(',')
            if (id.length == 0) {
              vui365.BsDialog.toast('没有勾选任何项目');
              return;
            }
          }
          if (!confirm('您确定要删除吗？\n记录编号：' + id)) {
            return;
          }
          const msgInfo = await vui365.stdAxios(UrlCfg.delete.replace('{id}', id), {}, "DELETE");
          console.log("[删除记录] msgInfo=", msgInfo, formData);
          if (msgInfo.status == 0) {
            vui365.BsDialog.alert(msgInfo.message);
            return;
          }
          vui365.globalApp.refreshDataTable()
        },
        // 处理复制事件
        async onCopy(id) {
          // console.log('复制',id);
          const msgInfo = await vui365.stdAxios(UrlCfg.copy, { id: id });
          console.log("[复制记录] msgInfo=", msgInfo, id);
          if (msgInfo.status == 0) {
            vui365.BsDialog.alert(msgInfo.message);
            return;
          }
          vui365.globalApp.refreshDataTable()
        },
        // 处理改变分页尺寸事件
        onChangePageSize(pageSize) {
          this.pageSize = pageSize;
          this.onRefresh();
        },
        // 处理分页事件
        onPaging(page) {
          this.page = page;
          this.onRefresh();
        },
        // 处理搜索事件
        onSearch(text) {
          this.searchText = text;
          this.onRefresh();
        },
        // 获取数剧列的配置内容
        getColumns(isForm = false) {
          let columns = [
            { name: "id", text: "ID", component: "text", view: "r" },
            {
              name: "attr_name",
              text: "属性名称",
              component: "text",
              view: "cru",
            },
            {
              name: "category_name",
              text: "商品类别",
              component: "text",
              view: "cru",
            },
            {
              name: "pid",
              text: "父级ID",
              component: "select",
              view: "cu",
            },
            {
              name: "sort",
              text: "排序",
              component: "number",
              view: "cru",
            },
            {
              name: "created_at",
              text: "创建时间",
              component: "text",
              view: "r",
            },
            {
              name: "status_text",
              text: "状态",
              component: "text",
              view: "r",
            },
          ];
          let data = [], isEdit = this.id > 0;
          for (let col of columns) {
            if (isForm) {
              if (isEdit && col.view.indexOf("u") > -1) {
                data.push(col);
              } else if (col.view.indexOf("c") > -1) {
                data.push(col);
              }
              continue;
            }
            if (col.view.indexOf("r") > -1) {
              data.push(col);
            }
          }
          return data;
        },
      },
      // created 生命周期方法
      created() {
        this.initData();
      },
      // mounted 生命周期方法
      mounted() {
        this.initView();
        window.$refreshDataTable = this.onRefresh
      },
    };

    // 创建应用实例
    const app = Vue.createApp(App);
    //  注册组件
    app.component("data-table-template", vui365.getComponentOfDataTableTemplate())
    app.component("tabsbar", vui365.getComponentOfTabsbar())
    app.component("toolbar", vui365.getComponentOfToolbar())
    app.component("searchbar", vui365.getComponentOfSearchbar())
    app.component("paginationbar", vui365.getComponentOfPaginationbar())
    // 加载根元素
    app.mount('#app');

    // 公开方法 - 刷新数据表
    function refreshDataTable() {
      window.$refreshDataTable();
    }
  </script>

</body>

</html>